package com.fjh.shop.orders.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjh.shop.common.exceptions.BusinessException;
import com.fjh.shop.common.exceptions.enums.Resp;
import com.fjh.shop.goods.feign.api.GoodsClient;
import com.fjh.shop.goods.model.vo.GoodsListDetailsVO;
import com.fjh.shop.orders.model.entity.Cart;
import com.fjh.shop.orders.model.entity.Order;
import com.fjh.shop.orders.model.entity.OrderItem;
import com.fjh.shop.orders.model.vo.CartItemVO;
import com.fjh.shop.orders.service.handlers.BaseContextHandler;
import com.fjh.shop.orders.service.mapper.OrderMapper;
import com.fjh.shop.orders.service.service.CartService;
import com.fjh.shop.orders.service.service.OrderItemService;
import com.fjh.shop.orders.service.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  订单服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-07-16
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private CartService cartService;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private GoodsClient goodsClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrder() {
        //todo: 订单号生成策略
        LocalDateTime now = LocalDateTime.now();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Random rand=new Random();
        long id = Long.parseLong(format.format(now) + rand.nextInt(8888888) + 1000000);
        //从购物车里面获取商品信息
        List<CartItemVO> cartItems = cartService.getCart();

        BigDecimal amount = this.orderItemService.addOrderItem(cartItems,id);

        Order order = new Order();
        order.setMemberId(BaseContextHandler.get());

        order.setId(id);
        order.setTotalAmount(amount);

        this.save(order);

        //清理购物车
        cartService.deleteCart();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteOrder(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Order updateOrder(Order order) {
        if (order == null || order.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        order.setUpdatedAt(new Date());
        this.updateById(order);
        return order;
    }

    @Override
    public Order getOrderById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.getById(id);
    }

    @Override
    public Page<Order> pageOrder(Integer current, Integer pageSize, Long orderId, String orderNo, Long memberId, Integer status) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        // 按订单ID查询
        if (orderId != null) {
            queryWrapper.eq(Order::getId, orderId);
        }

        // 按订单号模糊查询
        if (StringUtils.hasText(orderNo)) {
            queryWrapper.like(Order::getOrderNo, orderNo);
        }

        // 按会员ID查询
        if (memberId != null) {
            queryWrapper.eq(Order::getMemberId, memberId);
        }

        // 按订单状态查询
        if (status != null) {
            queryWrapper.eq(Order::getStatus, status);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(Order::getCreatedAt);

        return this.page(new Page<>(current, pageSize), queryWrapper);
    }
}
